package com.up.vms.interfaces.rest.utils;

import com.alibaba.fastjson.JSON;
import com.up.vms.infrastructure.security.Sign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class AuthUtil {

    public static final String YGH_SSO_URL = "http://thirdparty.test.nbpitech.com:8060/cas";

    public static final String CLIENT_ID = "client_id";
    public static final String NONCE_STR = "nonce_str";
    public static final String TIMESTAMP = "timestamp";
    public static final String VERSION = "version";
    public static final String CLIENT_SECRET = "client_secret";

    @Value("${ygh.clientId}")
    public String clientId;

    @Value("${ygh.clientSecret}")
    public String clientSecret;

    @Autowired
    HttpClientUtil httpClientUtil;

    public Map<String, Object> getToken(HashMap<String, Object> content) {
        HttpClientEntity entity = new HttpClientEntity();
        LinkedHashMap<String, String> headerMap = new LinkedHashMap<>();
        headerMap.put("client_id", "");
        headerMap.put("nonce_str", "");
        headerMap.put("timestamp", "");
        headerMap.put("version", "1.0");

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        long timeStampSec = System.currentTimeMillis()/1000;
        String timestamp = String.format("%010d", timeStampSec);

        String signValue = sign(this.clientId, uuid, timestamp);
        headerMap.put("sign", signValue);
        entity.setHeaders(headerMap);

        entity.setContentMap(content);
        entity.setResponseFormat("JSON");

        entity.setUrl(YGH_SSO_URL + "/userInfo");

        HttpClientResponseMsg msg = httpClientUtil.post(entity);

        String json = msg.getResult();

        Map result = JSON.parseObject(json);

        return result;
    }

    private String sign(String clientId, String uuid, String timestamp) {
        String signStr;
        try {
            Map<String, String> map = new HashMap<>();
            map.put(CLIENT_ID, clientId);


            map.put(NONCE_STR, uuid);


            map.put(TIMESTAMP, timestamp);
            map.put(VERSION, "1.0");

            String msgEncode = ParamUtil.formatUrlMap(map, false, false);

            String msgAdd = msgEncode + "&" + this.CLIENT_SECRET + "=" + clientSecret;

            signStr = Sign.sha256Encrypt(msgAdd.getBytes("utf-8")).toUpperCase();


        } catch (UnsupportedEncodingException e) {
            signStr = null;
        }
        return signStr;
    }
}
